<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-22 23:16:47
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-09-23 16:43:49
 * @FilePath: /task-admin/src/views/project/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="container">
    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :stripe="true"
      :content-config="contentConfig"
      @add-click="handleOpenDialog"
      @edit-click="handleEditClick"
      @view-click="handleViewClick"
    >
      <template #status="scope">
        <span
          class="table-status"
          :class="`status_${statusOptions[scope.row.status].value}`"
          >{{ statusOptions[scope.row.status].label }}</span
        >
      </template>

      <template #progress="scope">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="`${scope.row.schedule}%`"
          placement="top"
        >
          <el-progress :show-text="false" :percentage="scope.row.schedule" />
        </el-tooltip>
      </template>
      <template #estimated="scope">
        <span>{{ scope.row.estimated_amount }}</span>
      </template>
      <template #actual="scope">
        <span>{{ scope.row.actual_amount }}</span>
      </template>
    </page-content>

    <!-- 新增表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="890px"
      @close="handleCloseDialog"
    >
      <BasicInfoForm
        ref="basicInfoFormFormRef"
        :stakeholderOptions="stakeholderOptions"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!--编辑查看弹窗-->
    <el-drawer
      v-model="drawerDialog.visible"
      :title="drawerDialog.title"
      size="1200px"
      @close="handleDrawerCloseDialog"
    >
      <div class="drawer-box">
        <div class="bg-[#F2F3F5] p8 mb-4 flex justify-between">
          <ul class="flex flex-1 justify-between">
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectName")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ baseInfo?.p_name }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectNo")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ baseInfo?.p_no }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.projectLeader")
              }}</span>
              <p
                class="text-[#323233] m-0 ellipsis w-[100%] text-16px font-900 lh-24px"
              >
                {{ stakeholderObj[baseInfo?.p_manager as string] }}
              </p>
            </li>
            <li class="h-56px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.status")
              }}</span>
              <span
                class="table-status"
                :class="`status_${baseInfo?.status ? baseInfo?.status : 1}`"
                >{{
                  statusOptions[baseInfo?.status ? baseInfo?.status : 1].label
                }}</span
              >
            </li>
            <li class="h-56px w-190px pr-30px flex flex-col shrink-0">
              <span class="text-[#969799] text-14px font-500 lh-24px mb-8px">{{
                $t("common.progress")
              }}</span>
              <el-progress
                :text-inside="true"
                :stroke-width="24"
                :percentage="baseInfo?.schedule"
              />
            </li>
          </ul>
          <span
            @click="handleBdgexport(baseInfo?.id as string)"
            class="flex-center px-16px h-56px bg-[#4E6BEF] text-[#EEF0FD] text-14px cursor-pointer border-rd-3px shrink-0 ml-20px"
            ><svg-icon class="h4 w4 mr-2" icon-class="BudgetList" />{{
              $t("common.exportBudgetList")
            }}</span
          >
        </div>
        <el-tabs
          v-model="activeName"
          class="demo-tabs"
          @tab-click="handleTabClick"
        >
          <el-tab-pane name="first">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'first'
                      ? 'project-no-select'
                      : 'project-select'
                  "
                />
                {{ $t("common.basicInfo") }}
              </span>
            </template>
            <div
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.basicInfo") }}
            </div>
            <BasicInfoForm
              ref="basicInfoFormFormRef2"
              :stakeholderOptions="stakeholderOptions"
              :disabled="viewType == 2 ? false : true"
              :baseInfo="baseInfo"
            />
            <div
              class="flex h-52px px-16px py-15px border-rd-8px bg-[#F0F5FF] items-center text-[#323233] text-16px font-900"
            >
              <i class="i-ep:arrow-down w-1em h-1em mr-8px"></i
              >{{ $t("common.systemInfo") }}
            </div>
            <SystemForm :systemInfo="systemInfo" />
          </el-tab-pane>
          <el-tab-pane name="second">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'second' ? 'site-no-selected' : 'site-select'
                  "
                />
                {{ $t("common.projectSite") }}
              </span>
            </template>
            <!-- 列表 -->
            <SiteTable
              ref="addSiteTableRef"
              :siteInfo="siteInfo"
              :viewType="viewType"
            />
          </el-tab-pane>
          <el-tab-pane name="third">
            <template #label>
              <span class="custom-tabs-label">
                <svg-icon
                  class="w-14px h-14px mr-5px text-[#969799]"
                  :icon-class="
                    activeName !== 'third'
                      ? 'BudgetListNoSelect'
                      : 'BudgetListSelect'
                  "
                />
                {{ $t("common.projectBudget") }}
              </span>
            </template>
            <ProjectBudget :budgetInfo="budgetInfo" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <div class="dialog-footer" v-show="viewType == 2">
          <el-button type="primary" @click="handleDrawerSubmitClick">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleDrawerCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import type PageContent from "@/components/PageContent/index.vue";
import BasicInfoForm from "./components/BasicInfoForm/index.vue";
import SiteTable from "./components/SiteTable/index.vue";
import ProjectBudget from "./components/ProjectBudget/index.vue";

import contentConfig from "./config/content";
import { useRouter } from "vue-router";
import type { IObject } from "@/hooks/usePage";
import ProjectAPI from "@/api/project";
import { BaseInfo, SiteInfo, BudgetInfo } from "@/api/project/model";
import TaskAPI from "@/api/task";
import UserAPI from "@/api/user";
import type { TabsPaneContext } from "element-plus";

defineOptions({
  name: "ProjectLocation",
  inheritAttrs: false,
});
const router = useRouter();
const { t } = useI18n();
// 状态
const statusOptions = ref<Options[]>([
  {
    value: 0,
    label: t("common.all"),
  },
  {
    value: 1,
    label: t("common.inTheBiddingProcess"),
  },
  {
    value: 2,
    label: t("common.wonTheBid"),
  },
  {
    value: 3,
    label: t("common.notWinningTheBid"),
  },
]);

const stakeholderOptions = ref<Options[]>([]);
const stakeholderObj = reactive<{ [key: string]: string }>({});
const getUserList = async () => {
  const data = await UserAPI.getPage({
    page: 1,
    page_size: 10000,
  });
  if (data.list.length > 0) {
    stakeholderOptions.value = data.list.map((item) => {
      stakeholderObj[item.id] = item.nickname as string;
      return {
        value: item.id,
        label: `${item.nickname}`,
        mobile: item.mobile,
      };
    });
  }
};

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

const loading = ref(false);
const ids = ref<number[]>([]);
// 新增
function handleOpenDialog() {
  dialog.visible = true;
  dialog.title = t("common.addProject");
}
/** 关闭弹窗 */
const basicInfoFormFormRef = ref(ElForm);
function handleCloseDialog() {
  dialog.visible = false;
  basicInfoFormFormRef.value.projectFormRef.resetFields();
  basicInfoFormFormRef.value.projectFormRef.clearValidate();
  basicInfoFormFormRef.value.formData.id = undefined;
  basicInfoFormFormRef.value.formData.status = 1;
}

/** 提交表单 */
const contentRef = ref<InstanceType<typeof PageContent>>();
function handleSubmit() {
  basicInfoFormFormRef.value.projectFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const projectId = basicInfoFormFormRef.value.formData.id;
      ProjectAPI.add({ base_info: basicInfoFormFormRef.value.formData })
        .then(() => {
          ElMessage.success(
            projectId
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 弹窗
const drawerDialog = reactive({
  title: "",
  visible: false,
});

const activeName = ref("first");

const handleTabClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/** 关闭弹窗 */
const basicInfoFormFormRef2 = ref(ElForm);
function handleDrawerCloseDialog() {
  activeName.value = "first";
  drawerDialog.visible = false;
  basicInfoFormFormRef2.value.projectFormRef.resetFields();
  basicInfoFormFormRef2.value.projectFormRef.clearValidate();
  basicInfoFormFormRef2.value.formData.id = undefined;
  basicInfoFormFormRef2.value.formData.status = 1;
}

// 获取详情
const viewType = ref(2); //1: 查看 2:编辑
const baseInfo = ref<BaseInfo>();
const systemInfo = ref<SystemForm | undefined>();
const siteInfo = ref<SiteInfo[]>();
const budgetInfo = ref<BudgetInfo>();

const getDetail = (row: IObject) => {
  drawerDialog.visible = true;
  drawerDialog.title = row.p_name;
  ProjectAPI.detail({ id: row.id }).then((data) => {
    systemInfo.value = data.system_info;
    baseInfo.value = data.base_info;
    siteInfo.value = data.site_info;
    budgetInfo.value = data.budget_info;
    Object.assign(basicInfoFormFormRef2.value.formData, data.base_info);
  });
};

const addSiteTableRef = ref(ElForm);
const handleDrawerSubmitClick = () => {
  basicInfoFormFormRef2.value.projectFormRef.validate((valid: any) => {
    const site_info = addSiteTableRef.value.newSiteInfo;
    if (
      site_info.length > 0 &&
      site_info.some(
        (item: any) =>
          item.s_name === "" ||
          item.s_address === "" ||
          item.s_postalcode === "" ||
          item.start_d === "" ||
          item.end_d === ""
      )
    ) {
      ElMessage.error(t("common.pleaseFillFirst"));
      return;
    }
    if (valid) {
      loading.value = true;
      const Id = basicInfoFormFormRef2.value.formData.id;
      ProjectAPI.add({
        base_info: basicInfoFormFormRef2.value.formData,
        site_info: site_info.map((item: any) => {
          return {
            id: item.id == "-1" ? undefined : item.id,
            s_name: item.s_name,
            s_address: item.s_address,
            s_postalcode: item.s_postalcode,
            start_d: item.start_d,
            end_d: item.end_d,
            status: item.status,
          };
        }),
      })
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleDrawerCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      activeName.value = "first";
      ElMessage.error(t("common.completeInfo"));
    }
  });
};
const projectId = ref("");

// 查看
const handleViewClick = (row: IObject) => {
  projectId.value = row.id;
  viewType.value = 1;
  getDetail(row);
};

// 编辑
const handleEditClick = (row: IObject) => {
  projectId.value = row.id;
  viewType.value = 2;
  getDetail(row);
};

// 导出
const handleBdgexport = (id: string) => {
  ProjectAPI.bdgexport({ id: id }).then((data) => {
    console.log("%c Line:437 🧀 data", "color:#e41a6a", data);

    const downloadLink = document.createElement("a");
    downloadLink.href = data.file;
    downloadLink.download = `${t("common.budgetTable")}.xlsx`;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    window.URL.revokeObjectURL(data.file);
  });
};

onMounted(() => {
  getUserList();
});
</script>

<style scoped>
/* @import url(); 引入公共css类 */
</style>
